*--------------------------------------------------
* Program Setup
*--------------------------------------------------
set more off            // Disable partitioned output
clear all               // Start with a clean slate
set linesize 80         // Line size limit to make output more readable
macro drop _all         // clear all macros
*--------------------------------------------------

*--------------------------------------------------
* Global macros
*--------------------------------------------------

* Working directory (change this to your working director)
global workpath "D:\Dropbox\Research\Projects\LocalPolitics\drafts\paper\rcfs\final\replication"

* Global cluster variable
global clustvars "st_fips naicsh4dN"

* Set global scheme
set scheme white_tableau2

* Open log
cd "$workpath"
log using 2_analysis, replace

************************************************************************************************************
/********************************* Firm panel analysis***************************************/
************************************************************************************************

* Load data
cd "$workpath"
use intermediate\localpolitics_firmpanel.dta, clear

* Label variables
label variable pivotal "Swing"
label variable tight "BalSenate"
label variable pivotal_tight "Swing x BalSenate"
label variable capx_lassets "CapEx"
label variable xsga_lassets "SG\&A"
label variable xrd_lassets "R\&D"
label variable txfed_etr "FedTaxETR"
label variable txfo_etr "ForeignTaxETR"
label variable txs_etr "StateTaxETR"
label variable levltb "Leverage"
label variable ebitda_lassets "ROA"
label variable profit "Profitability"
label variable sale_gr "SaleGr"
label variable ln_sale_gr "lnSaleGr"
label variable tq "TobinsQ"
label variable subsidyamt_tot_sale "SubsidyTot"
label variable subsidyamt_allgrants_sale "SubsidyOthGrant"
label variable subsidyamt_fedgrant_sale "SubsidyFedGrant"
label variable subsidyamt_grants_sale "SubsidyNonFedGrant"
label variable subsidyamt_tax_sale "SubsidyTax"
label variable subsidyamt_taxcredit_sale "SubsidyTaxCredit"
label variable subsidyamt_proptax_sale "SubsidyPropTax"
label variable senatorsD "Democrat"
label variable senatorsR "Republican"
label variable majpty "MajPty"
label variable minpty "MinPty"
label variable ln_sentenure "lnSenTenure"
label variable haschair_top1 "CommChairTop1"
label variable haschair_top3 "CommChairTop3"
label variable haschair_top5 "CommChairTop5"

*--------------------------------------------------
* Firm-level macros
*--------------------------------------------------

global firmfilters "!indfilter"
global firmfevars "gvkey fyear"
global ctrlvars "senatorsD senatorsR majpty minpty haschair_top1 haschair_top3 haschair_top5"
global firmclustvars "st_fips naicsh4dN"

*--------------------------------------------------
* Table II - Firm-level Summary Statistics
*--------------------------------------------------

* Table II Panel B - rows 1-4
eststo clear
foreach type in taxcredit proptax fedgrant grants {
	quietly estpost tabstat subsidyamt_`type'_sale if $firmfilters & subsidizedfirm_`type', stat(count mean sd p25 med p75) columns(statistics)

	* Working Output
	esttab, nonum noobs nonote compress label ///
	cells("count(label(Observations) fmt(%9.0fc)) mean(label(Mean) fmt(%9.3f)) sd(label(Std Dev) fmt(%9.3f)) p25(label(P25) fmt(%9.3f)) p50(label(Median) fmt(%9.3f)) p75(label(P75) fmt(%9.3f))") 
}


* Table II Panel B - rows 5-14
eststo clear
local mainvars`' "tq capx_lassets xsga_lassets xrd_lassets"
local othervars "sale_gr ebitda_lassets profit levltb"
local taxvars "txfed_etr txs_etr txfo_etr"
quietly estpost tabstat `mainvars' `othervars'  `taxvars' if $firmfilters, stat(count mean sd p25 med p75) columns(statistics)

* Working Output
esttab, nonum noobs nonote compress label ///
cells("count(label(Observations) fmt(%9.0fc)) mean(label(Mean) fmt(%9.3f)) sd(label(Std Dev) fmt(%9.3f)) p25(label(P25) fmt(%9.3f)) p50(label(Median) fmt(%9.3f)) p75(label(P75) fmt(%9.3f))") 

*--------------------------------------------------
* Tables V and B1 - Effect on Firm-Level Subsidies
*--------------------------------------------------

* Table V - unrestricted sample
local rhsvar "pivotal pivotal_tight"
eststo clear
foreach lhsvar in subsidyamt_taxcredit_sale subsidyamt_proptax_sale subsidyamt_grants_sale subsidyamt_fedgrant_sale {
	eststo `lhsvar': quietly reghdfe `lhsvar' `rhsvar' if $firmfilters, absorb($firmfevars) cluster($firmclustvars)
	quietly estadd local FEfirm "X"
	quietly estadd local FEyear "X"	
}

* Working output
esttab, keep(pivotal*) b(%5.4f) se(%8.4f) star(* 0.1 ** 0.05 *** 0.01) par depvars label collabels(none) ar2 ///
s(FEfirm FEyear N r2_a, label("Firm FE" "Year FE" "Observations" "Adjusted R-squared") fmt(0 0 %9.0fc 3)) nonotes // bottom summary

* Table B1 - Restricted Sample
local rhsvar "pivotal pivotal_tight"
eststo clear
foreach type in taxcredit proptax grants fedgrant {
	eststo `type': quietly reghdfe subsidyamt_`type'_sale `rhsvar' if $firmfilters & subsidizedfirm_`type'==1, absorb($firmfevars) cluster($firmclustvars)
	quietly estadd local FEfirm "X"
	quietly estadd local FEyear "X"	
}


* Working output
esttab, keep(pivotal*) b(%5.4f) se(%8.4f) star(* 0.1 ** 0.05 *** 0.01) par depvars label collabels(none) ar2 ///
s(FEfirm FEyear N r2_a, label("Firm FE" "Year FE" "Observations" "Adjusted R-squared") fmt(0 0 %9.0fc 3)) nonotes // bottom summary

*--------------------------------------------------
* Table VI - Investment Findings
*--------------------------------------------------

* Run regressions
local rhsvar "pivotal pivotal_tight"
local ctrlvars1 ""
local ctrlvars2 "$ctrlvars"
local ctrlvarlab1 "No"
local ctrlvarlab2 "Yes"
eststo clear
forvalues i = 1/2 {
	foreach lhsvar in tq capx_lassets xsga_lassets xrd_lassets {
		eststo `lhsvar'`i': quietly reghdfe `lhsvar' `rhsvar' `ctrlvars`i'' if $firmfilters, absorb($firmfevars) cluster($firmclustvars)
		quietly estadd local FEfirm "X"
		quietly estadd local FEyear "X"	
		quietly estadd local CtrlVars "`ctrlvarlab`i''"
	}
}

* Working output
esttab, b(%5.4f) se(%8.4f) order(pivotal*) star(* 0.1 ** 0.05 *** 0.01) par depvars label collabels(none) ar2 noconstant ///
s(CtrlVars FEfirm FEyear N r2_a, label("Control Variables" "Firm FE" "Year FE" "Observations" "Adjusted R-squared") fmt(0 0 0 %9.0fc 3)) nonotes // bottom summary

*--------------------------------------------------
* Table VII - Operating Performance
*--------------------------------------------------

* Run regressions
local rhsvar "pivotal pivotal_tight"
local ctrlvars "$ctrlvars"
eststo clear
foreach lhsvar in ln_sale_gr ebitda_lassets profit levltb {
	eststo `lhsvar': quietly reghdfe `lhsvar' `rhsvar' `ctrlvars' if $firmfilters, absorb($firmfevars) cluster($firmclustvars)
	quietly estadd local FEfirm "X"
	quietly estadd local FEyear "X"	
	quietly estadd local CtrlVars "Yes"
}


* Working output
esttab, b(%5.4f) se(%8.4f) keep(pivotal*) star(* 0.1 ** 0.05 *** 0.01) par depvars label collabels(none) ar2 ///
s(CtrlVars FEfirm FEyear N r2_a, label("Control Variables" "Firm FE" "Year FE" "Observations" "Adjusted R-squared") fmt(0 0 0 %9.0fc 3)) nonotes // bottom summary


*--------------------------------------------------
* Table X - Taxes
*--------------------------------------------------

* Run regressions
local rhsvar "pivotal pivotal_tight"
local fevars1 "gvkey fyear"
local fevars2 "gvkey fyear indyr"
local indyrfelab1 ""
local indyrfelab2 "X"
eststo clear
forvalues i=1/2 {
	foreach lhsvar in txfed_etr txs_etr txfo_etr {
		eststo `lhsvar'`i': quietly reghdfe `lhsvar' `rhsvar' $ctrlvars if $firmfilters, absorb(`fevars`i'') cluster($firmclustvars)
		quietly estadd local FEfirm "X"
		quietly estadd local FEyear "X"	
		quietly estadd local FEindyr "`indyrfelab`i''"	
	}
}

* Working output
esttab, keep(pivotal*) b(%5.4f) se(%8.4f) star(* 0.1 ** 0.05 *** 0.01) par depvars label collabels(none) ar2 ///
s(FEfirm FEyear FEindyr N r2_a, label("Firm FE" "Year FE" "NAICS4-Year FE" "Observations" "Adjusted R-squared") fmt(0 0 0 %9.0fc 3)) nonotes // bottom summary

*--------------------------------------------------
* Table B2 - Heterogeneity in Import Penetration Exposure
*--------------------------------------------------

* Cut by trade exposure (MFG industries only)
local cut "hightrade"
eststo clear
local rhsvars "`cut' pivotal pivotal_tight pivotal_`cut' `cut'_tight pivotal_`cut'_tight"
foreach lhsvar in tq capx_lassets xsga_lassets xrd_lassets {
	eststo `lhsvar'`cut': quietly reghdfe `lhsvar' `rhsvars' $ctrlvars if $firmfilters, absorb($firmfevars) cluster($firmclustvars)
	quietly estadd local FEfirm "X"
	quietly estadd local FEyear "X"	
}

* Working output
esttab, keep(hightrade* pivotal*) order(pivotal hightrade*) b(%5.4f) se(%8.4f) star(* 0.1 ** 0.05 *** 0.01) par depvars label collabels(none) ar2 ///
s(FEfirm FEyear N r2_a, label("Firm FE" "Year FE" "Observations" "Adjusted R-squared") fmt(0 0 %9.0fc 3)) nonotes // bottom summary

*--------------------------------------------------
* Table B3 - Regulated vs. non-regulated industries
*--------------------------------------------------

* Run regressions
label variable reg "Regulated"
label variable reg_tight "Regulated x BalSenate"
label variable pivotal_reg "Swing x Regulated"
label variable pivotal_tradable "Swing x Tradable"
label variable pivotal_reg_tight "Swing x Regulated x BalSenate"
label variable hightrade "HighIPR"
label variable hightrade_tight "HighIPR x BalSenate"
label variable tradable_tight "Tradable x BalSenate"
label variable pivotal_hightrade "Swing x HighIPR"
label variable pivotal_hightrade_tight "Swing x HighIPR x BalSenate"
label variable pivotal_tradable_tight "Swing x Tradable x BalSenate"

* Cut by industry regulation
local cut "reg"
eststo clear
local rhsvars "`cut' pivotal pivotal_tight pivotal_`cut' `cut'_tight pivotal_`cut'_tight"
foreach lhsvar in tq capx_lassets xsga_lassets xrd_lassets {
	eststo `lhsvar'`cut': quietly reghdfe `lhsvar' `rhsvars' $ctrlvars if $firmfilters, absorb($firmfevars) cluster($firmclustvars)
	quietly estadd local FEfirm "X"
	quietly estadd local FEyear "X"	
}

* Working output
esttab, keep(reg* pivotal*) order(pivotal reg*) b(%5.4f) se(%8.4f) star(* 0.1 ** 0.05 *** 0.01) par depvars label collabels(none) ar2 ///
s(FEfirm FEyear N r2_a, label("Firm FE" "Year FE" "Observations" "Adjusted R-squared") fmt(0 0 %9.0fc 3)) nonotes // bottom summary

*--------------------------------------------------
* Figure II and Figure IV - Firm-Level Dynamics
*--------------------------------------------------

* Generate time relative to 2000/2016
gen pivotal_yrm4 = pivotal * inlist(fyear,1996,2012)
gen pivotal_yrm3 = pivotal * inlist(fyear,1997,2013)
gen pivotal_yrm2 = pivotal * inlist(fyear,1998,2014)
gen pivotal_yrm1 = pivotal * inlist(fyear,1999,2015)
gen pivotal_yr0 = pivotal * inlist(fyear,2000,2016)
gen pivotal_yr1 = pivotal * inlist(fyear,2001,2017)
gen pivotal_yr2 = pivotal * inlist(fyear,2002,2018)
gen pivotal_yr3 = pivotal * inlist(fyear,2003,2019)
gen pivotal_yr4 = pivotal * inlist(fyear,2004,2020)

* Label variables
label variable pivotal_yrm4 "-4"
label variable pivotal_yrm3 "-3"
label variable pivotal_yrm2 "-2"
label variable pivotal_yrm1 "-1"
label variable pivotal_yr0 "0"
label variable pivotal_yr1 "1"
label variable pivotal_yr2 "2"
label variable pivotal_yr3 "3"
label variable pivotal_yr4 "4"

* Dynamics for Figure II
local rhsvar "pivotal pivotal_yrm3-pivotal_yr3"
local filters "!indfilter & inrange(fyear,1997,2019)"
eststo clear
foreach lhsvar of varlist tq capx_lassets xsga_lassets xrd_lassets ln_sale_gr ebitda_lassets profit levltb {
	eststo `lhsvar': quietly reghdfe `lhsvar' `rhsvar' $ctrlvars if `filters', absorb($firmfevars) cluster($firmclustvars)	
	quietly estadd local FEfirm "X"
	quietly estadd local FEyear "X"

	coefplot, keep(pivotal_*) yline(0, lcolor(black)) vertical coeflabels(, wrap(4)) ///
	xline(4, lpattern("-"))  levels(95) omitted recast(connected) lpattern(-) ///
	ytitle("Coefficient and 95th CI for Swing x I({&tau})") xtitle("Year Relative to Election ({&tau})")
	graph export output\figures\dynamicsboth_`lhsvar'.png, replace	
}


* Dynamics for Figure IV
local rhsvar "pivotal pivotal_yrm3-pivotal_yr3"
local filters "!indfilter & inrange(fyear,1997,2019)"
eststo clear
foreach lhsvar of varlist txfed_etr {
	eststo `lhsvar': quietly reghdfe `lhsvar' `rhsvar' $ctrlvars if `filters', absorb($firmfevars) cluster($firmclustvars)	
	quietly estadd local FEfirm "X"
	quietly estadd local FEyear "X"

	coefplot, keep(pivotal_*) yline(0, lcolor(black)) vertical coeflabels(, wrap(4)) ///
	xline(4, lpattern("-"))  levels(95) omitted recast(connected) lpattern(-) ///
	ytitle("Coefficient and 95th CI for Swing x I({&tau})") xtitle("Year Relative to Election ({&tau})")
	graph export output\figures\dynamicsboth_`lhsvar'.png, replace	
}


************************************************************************************************************
/********************************* State panel analysis***************************************/
************************************************************************************************

* Load data
cd "$workpath"
use intermediate\localpolitics_statepanelfinal.dta, clear

* Label variables

label variable ln_amtspend_contracts "lnContracts"
label variable ln_amtspend_grants "lnGrants"
label variable ln_amtspend_loan "lnLoans"
label variable ln_amtspend_payment "lnPayments"
label variable ln_amtspend_other "lnOtherAssistance"
label variable ln_amtspend_tot "lnTotSpend"
label variable ln_emp_priv "lnEmp"
label variable ln_wages_priv "lnWage"
label variable ln_estabs_priv "lnEstab"

foreach type in 0to19 20to49 50to249 250to499 500plus {
	label variable ln_qemps_`type'emps "lnEmps`type'"
}


* Label variables
label variable absvotediff "PresVoteMargin"
label variable pivotal "Swing"
label variable tight "BalSenate"
label variable pivotal_tight "Swing x BalSenate"

*--------------------------------------------------
* State-level macros
*--------------------------------------------------

global stfevars "st_fips year"
global stctrlvars "senatorsD senatorsR majpty minpty ln_pop ln_sentenure"
global stclustvars "st_fips"

*--------------------------------------------------
* Table II Panel A - Summary statistics
*--------------------------------------------------

* Label
label variable amtspend_tot "TotSpend (\$bn)"
label variable amtspend_contracts "Contracts (\$bn)"
label variable amtspend_grants "Grants (\$bn)"
label variable amtspend_loan "Loans (\$bn)"
label variable amtspend_payment "Payments (\$bn)"
label variable gdp_real "GDP (\$bn)"
label variable emp_priv "Emp (mil)"
label variable wages_priv "Wage (\$bn)"
label variable estabs_priv "Estab (mil)"


* State-level summary statistics
eststo clear
local rhsvars "absvotediff"
local govspendvars "amtspend_tot amtspend_contracts amtspend_grants amtspend_loan amtspend_payment"
local tradevars "import_gr_wtemp tariffrate_wtemp"
local econvars "gdp_real emp_priv wages_priv estabs_priv"
quietly estpost tabstat `rhsvars' `govspendvars' `econvars', stat(count mean sd p25 med p75) columns(statistics)

* Working Output
esttab, nonum noobs nonote compress label ///
cells("count(label(Observations) fmt(%9.0fc)) mean(label(Mean) fmt(%9.3f)) sd(label(Std Dev) fmt(%9.3f)) p25(label(P25) fmt(%9.3f)) p50(label(Median) fmt(%9.3f)) p75(label(P75) fmt(%9.3f))") 

*--------------------------------------------------
* Table IV - Effect on Government Spending
*--------------------------------------------------

* Run regressions
local rhsvar "pivotal pivotal_tight"
eststo clear
foreach lhsvar of varlist ln_amtspend_tot ln_amtspend_contracts ln_amtspend_grants ln_amtspend_loan ln_amtspend_payment {
	eststo `lhsvar': quietly reghdfe `lhsvar' `rhsvar', absorb($stfevars) cluster($stclustvars)
	quietly estadd local FEstate "X"
	quietly estadd local FEyear "X"	
}

* Working output
esttab, keep(pivotal*) b(%5.4f) se(%8.4f) star(* 0.1 ** 0.05 *** 0.01) par depvars label collabels(none) ar2 ///
s(FEstate FEyear N r2_a, label("State FE" "Year FE" "Observations" "Adjusted R-squared") fmt(0 0 %9.0fc 3)) nonotes // bottom summary

*--------------------------------------------------
* Table VIII - Panel A
*--------------------------------------------------

* Label variables
label variable ln_gdp_real "lnGDP"
label variable ln_emp_priv "lnEmp"
label variable ln_wages_priv "lnWages"
label variable ln_estabs_priv "lnEstabs"

* Run regressions
local rhsvar "pivotal pivotal_tight"
eststo clear
foreach lhsvar of varlist ln_gdp_real ln_emp_priv ln_wages_priv ln_estabs_priv {
	eststo `lhsvar': quietly reghdfe `lhsvar' `rhsvar', absorb($stfevars) cluster($stclustvars)
	quietly estadd local FEstate "X"
	quietly estadd local FEyear "X"	
}

* Working output
esttab, keep(pivotal*) b(%5.4f) se(%8.4f) star(* 0.1 ** 0.05 *** 0.01) par depvars label collabels(none) ar2 ///
s(FEstate FEyear N r2_a, label("State FE" "Year FE" "Observations" "Adjusted R-squared") fmt(0 0 %9.0fc 3)) nonotes // bottom summary

*--------------------------------------------------
* Table VIII - Panel B
*--------------------------------------------------

* QWI employment - by size
local rhsvar "pivotal pivotal_tight"
eststo clear
foreach lhsvar of varlist ln_qemps_*emps {
	eststo `lhsvar': quietly reghdfe `lhsvar' `rhsvar', absorb($stfevars) cluster($stclustvars)
	quietly estadd local FEstate "X"
	quietly estadd local FEyear "X"	
}

* Working output
esttab, keep(*pivotal*) b(%5.4f) se(%8.4f) star(* 0.1 ** 0.05 *** 0.01) par depvars label collabels(none) ar2 ///
s(FEstate FEyear N r2_a, label("State FE" "Year FE" "Observations" "Adjusted R-squared") fmt(0 0 %9.0fc 3)) nonotes // bottom summary

************************************************************************************************************
/********************************* Legvoting analysis***************************************/
************************************************************************************************

* Load data
cd "$workpath"
use intermediate\localpolitics_legovtes_billfinal.dta, clear

* Label variables
label variable absvotediff "PresVoteMargin"
label variable votedev "LegVoteDev"

*--------------------------------------------------
* Figure I - bin scatterplots
*--------------------------------------------------

* Bin scatterplot - all bills
binscatter votedev absvotediff if congress>=103 & inlist(party_code,100,200), n(15) xtitle(PresVoteMargin) ytitle(LegVoteDev)
graph export output\figures\presmargin_votedev_scatter_all.png, replace

binscatter votedev absvotediff if congress>=103 & inlist(party_code,100,200) & budget == 1, n(15) xtitle(PresVoteMargin) ytitle(LegVoteDev (Budget))
graph export output\figures\presmargin_votedev_scatter_budget.png, replace

binscatter votedev absvotediff if congress>=103 & inlist(party_code,100,200) & budget == 0, n(15) xtitle(PresVoteMargin) ytitle(LegVoteDev (Non-Budget))
graph export output\figures\presmargin_votedev_scatter_nonbudget.png, replace

binscatter votedev absvotediff if congress>=103 & inlist(party_code,100,200) & regulation == 1, n(15) xtitle(PresVoteMargin) ytitle(LegVoteDev (Regulation))
graph export output\figures\presmargin_votedev_scatter_reg.png, replace

binscatter votedev absvotediff if congress>=103 & inlist(party_code,100,200) & regulation == 0, n(15) xtitle(PresVoteMargin) ytitle(LegVoteDev (Non-Regulation))
graph export output\figures\presmargin_votedev_scatter_nonreg.png, replace


************************************************************************************************************
/********************************* GA runoff analysis***************************************/
************************************************************************************************

* Load data
cd "$workpath"
use intermediate\eventstudy_abnormalrets_final.dta, clear

* Generate conditional variables
foreach var of varlist retadj ar_capm ar_ff3 {
	gen `var'_window = `var' if inrange(eventtdate,-1,1)
}

foreach var of varlist cumret car_capm car_ff3 {
	gen `var'_10= `var' if eventtdate == 10
	gen `var'_60= `var' if eventtdate == 60
}

* Label variables
label variable swingstate "Swing"
label variable absvotediff "PresVoteMargin"
label variable retadj "RawRet"
label variable ar_capm "AR_CAPM"
label variable ar_ff3 "AR_FF3"
label variable retadj_window "RawRet"
label variable ar_capm_window "AR_CAPM"
label variable ar_ff3_window "AR_FF3"
label variable cumret_10 "CumRet_10"
label variable car_capm_10 "CAR_CAPM_10"
label variable car_ff3_10 "CAR_FF3_10"
label variable cumret_60 "CumRet_60"
label variable car_capm_60 "CAR_CAPM_60"
label variable car_ff3_60 "CAR_FF3_60"
label variable cumret "CumRet"
label variable car_capm "CAR_CAPM"
label variable car_ff3 "CAR_FF3"

* Set scheme
set scheme white_tableau2

*--------------------------------------------------
* Table II Panel C - Summary Statistics
*--------------------------------------------------

* CAR summary statistics
eststo clear
local filters1 "eventtdate==1"
local filters2 "eventtdate==60"
local hor1 "1"
local hor2 "60"
local retvars "cumret car_capm car_ff3"
forvalues i=1/2 {
	quietly estpost tabstat `retvars' if `filters`i'', stat(count mean sd p25 med p75) columns(statistics)

	* Working Output
	esttab, nonum noobs nonote compress label ///
	cells("count(label(Observations) fmt(%9.0fc)) mean(label(Mean) fmt(%9.3f)) sd(label(Std Dev) fmt(%9.3f)) p25(label(P25) fmt(%9.3f)) p50(label(Median) fmt(%9.3f)) p75(label(P75) fmt(%9.3f))") 

}

*--------------------------------------------------
* Table IX - Event Study
*--------------------------------------------------

* Cumulative returns
local rhsvar "swingstate"
local filters1 "eventtdate==1"
local filters2 "eventtdate==60"
local filterlab1 "[-10,1]"
local filterlab2 "[-10,60]"
eststo clear
forvalues i=1/2 {
	foreach lhsvar in cumret car_capm car_ff3 {
		eststo `lhsvar'`i': quietly reg `lhsvar' `rhsvar' if `filters`i'', cluster(st_fips)
		quietly estadd local FilterLab "`filterlab`i''"
 
	}
}

* Working output
esttab, b(%5.4f) se(%8.4f) star(* 0.1 ** 0.05 *** 0.01) noconstant par depvars label collabels(none) ar2 ///
s(FilterLab N r2_a, label("CAR Window" "Observations" "Adjusted R-squared") fmt(0 %9.0fc 3)) nonotes // bottom summary

*--------------------------------------------------
* Figure B3 - Daily Returns Event Study
*--------------------------------------------------

* Run cross-sectional regression for each day
local rhsvar "swingstate"
eststo clear
foreach lhsvar in retadj ar_capm ar_ff3 {
	levelsof date if inrange(eventtdate,-6,5) & !missing(`lhsvar'), local(thedates)
	foreach t in `thedates' {
		eststo `lhsvar'`t': quietly reg `lhsvar' `rhsvar' if date==`t', cluster(st_fips) 		
		quietly estadd local FilterLab "`t'"
	}
}

* Create plots for each dependent variable
foreach lhsvar in retadj ar_capm ar_ff3 {
    
    * Clear any existing data for plotting
    preserve
    clear
    
    * Get the list of dates again (only dates with data)
    restore, preserve
    levelsof date if inrange(eventtdate,-6,5) & !missing(`lhsvar'), local(thedates)
    
    * Create temporary dataset to store coefficients
    clear
    gen seq = .
    gen date = .
    gen coef = .
    gen se = .
    gen ci_lower = .
    gen ci_upper = .
    
    local row = 1
    foreach t in `thedates' {
        * Check if estimate exists for this date
        capture estimates restore `lhsvar'`t'
        if _rc == 0 {
            * Extract coefficient and SE from stored estimation
            matrix b = e(b)
            matrix V = e(V)
            
            quietly set obs `row'
            quietly replace seq = `row' in `row'
            quietly replace date = `t' in `row'
            quietly replace coef = b[1,1] in `row'
            quietly replace se = sqrt(V[1,1]) in `row'
            quietly replace ci_lower = coef - 1.96*se in `row'
            quietly replace ci_upper = coef + 1.96*se in `row'
            
            local row = `row' + 1
        }
    }
    
    * Format the date variable for labels
    format date %td
    
    * Create custom xlabel with all dates
    local xlabels ""
    forvalues i = 1/`=_N' {
        local d = date[`i']
        local datelabel : display %td `d'
        local xlabels `"`xlabels' `i' "`datelabel'""'
    }
    
    * Create the plot using sequence number
    twoway (rcap ci_lower ci_upper seq, lcolor(gs10)) ///
           (scatter coef seq, mcolor(navy) msize(medium)), ///
           xlabel(`xlabels', angle(45) labsize(small)) ///
           ylabel(, format(%9.4f)) ///
           ytitle("Coefficient on Swing") ///
           xtitle("Estimation Date") ///
           legend(off) ///
           yline(0, lcolor(red) lpattern(dash)) ///
           xline(6, lcolor(red) lpattern(dot))
    
    graph export "$workpath\output\figures\\`lhsvar'_coefplot.png", replace
    
    restore
}


************************************************************************************************************
/********************************* Plotting event study ***************************************/
************************************************************************************************

* Load data
cd "$workpath"
use intermediate\eventstudy_abnormalrets_plots.dta, clear

*--------------------------------------------------
* Plotting global macros
*--------------------------------------------------

* Set scheme
set scheme white_tableau2

* Date thresholds
global elecday = td(5jan2021)
global budgday = td(4feb2021)
global firstday = td(22dec2020)
global lastday= td(30mar2021)
global budgday2= td(5mar2021)

*--------------------------------------------------
* Figure III - Subfigures (a) - (c)
*--------------------------------------------------

* Raw means
local filter "inrange(eventtdate,-10,60)"
local retvar1 "cumret"
local retvar2 "car_capm"
local retvar3 "car_ff3"
local ylab1 "Cumulative Returns (Raw)"
local ylab2 "Cumulative Abnormal Returns (CAPM)"
local ylab3 "Cumulative Abnormal Returns (FF3)"
forvalues i=1/3 {
	twoway 	line `retvar`i''0 `retvar`i''1 date if `filter', xaxis(1 2) ///
			xline($elecday $budgday $budgday2,lpattern(dash) lcolor(red)) ///
			xlabel($firstday[5]$lastday, labsize(small) angle(45) axis(1)) ///
			xlabel($elecday "GA Run-off" $budgday "Budget Resolution" $budgday2 "Budget Reconciliation", labsize(small) axis(2)) xscale(lstyle(none) axis(2)) ///
			xtitle("Date", axis(1)) xtitle("", axis(2)) ytitle(`ylab`i'') ///
			legend(order(1 "Partisan-State Firms" 2 "Swing-State Firms"))
	graph export output\figures\ga_eventstudy_`retvar`i''_rawmeans.png, replace
}

*--------------------------------------------------
* Figure III - Subfigures (d) - (f)
*--------------------------------------------------

* Error band  diff
local filter "inrange(eventtdate,-10,60)"
local retvar1 "cumret_diff"
local retvar2 "car_capm_diff"
local retvar3 "car_ff3_diff"
local ylab1 "Difference in Cumulative Returns (Raw)"
local ylab2 "Difference in Cumulative Abnormal Returns (CAPM)"
local ylab3 "Difference in Cumulative Abnormal Returns (FF3)"
forvalues i=1/3 {
	twoway 	(line `retvar`i'' date if `filter', xaxis(1 2)) ///		
			(rcap `retvar`i''lb `retvar`i''ub date if `filter', ///
			yline(0) xline($elecday $budgday $budgday2,lpattern(dash)) ///
			xlabel($firstday[5]$lastday, labsize(small) angle(45) axis(1)) ///
			xlabel($elecday "GA Run-off" $budgday "Budget Resolution" $budgday2 "Budget Reconciliation", labsize(small) axis(2)) ///
			xtitle("Date", axis(1)) xtitle("", axis(2)) ytitle(`ylab`i'') legend(off))
			graph export output\figures\ga_eventstudy_`retvar`i''_cibands.png, replace
}


************************************************************************************************************

* Close log
log close
